package com.xinnet.mms.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import junit.framework.Assert;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.AutoCustomer;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.allot.service.CustomMixService;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.CustomMix;
import com.xinnet.mms.entity.CustomMixAudit;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.EmpCustomer;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.DateUtil;

//客户分配控制层
@Controller
@RequestMapping("/allot")
public class CustomAllotController{
	@Autowired
	private CustomAllotDao customAllotDao;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private CustomerManageService customerManageService;
	@Autowired
	private CustomMixService customMixService;
	@Autowired
	private EmpCustomRelationService empCustomRelationService;
	@Autowired
	private EmpService empService;
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private CustomerStateHistService customerStateHistService;
	
	
	ObjectMapper mapper = new ObjectMapper();
	/**
	 * 
	 * 功能描述：调用分配新注册客户
	 *
	 * @param request
	 * @param response
	 * @return
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 *
	 * @since 2014年1月13日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/newcustom")
	public String allotNewCustom(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String deptno=request.getParameter("deptno");
		String cusId=request.getParameter("cusId");
		String pusherId=request.getParameter("pusherId");
		String typeData=request.getParameter("customerType");
		
		Customer custom=new Customer();
		
		int customerType=200;
		if(typeData!=null&&!typeData.equals(""))
			customerType=Integer.parseInt(typeData);
		else {
			custom.setAreaName("北京市");
			custom.setCname("呵呵李丽华");
			custom.setCustomerSource("400电话");
			custom.setCustomerType(0);
			custom.setEmail(UUID.randomUUID().toString().substring(0,10));
			custom.setIsAllot(0);
			custom.setIsReDevel(0);
			custom.setPhone(UUID.randomUUID().toString().substring(0,10));
			custom.setProductLabel("1");
			custom.setProductName("云主机");
			custom.setRegionalId("1");
			custom.setReportedEmpId("");
			custom.setCusId(UUID.randomUUID().toString());
			custom.setPusherId("system");
			customAllotService.allot(custom,customerType);
			return "market/login";
		}
		custom.setCusId(cusId);
		custom.setDeptno(deptno);
		custom.setPusherId(pusherId);
		
		customAllotService.allot(custom,customerType);
		return "market/login";
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/yj")
	public void testyj(HttpServletResponse response) throws Exception {
		Customer customer=AutoCustomer.makeNewCustomer("110100","北京市","3","邮局",CustomerManage.NEW_CUSTOMER);
		customerManageService.addCustom(customer);
		customAllotService.allot(customer,CustomerManage.NEW_CUSTOMER);
		PrintWriter out=response.getWriter();
		out.print(customer.getCusId());
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/xj")
	public void testxj(HttpServletResponse response) throws Exception {
		Customer customer=AutoCustomer.makeNewCustomer("110100","北京市","2","虚机s",CustomerManage.NEW_CUSTOMER);
		customerManageService.addCustom(customer);
		customAllotService.allot(customer,CustomerManage.NEW_CUSTOMER);
		PrintWriter out=response.getWriter();
		out.print(customer.getCusId());
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/ym")
	public void testym(HttpServletResponse response) throws Exception {
		Customer customer=AutoCustomer.makeNewCustomer("110100","北京市","1","域名",CustomerManage.NEW_CUSTOMER);
		customerManageService.addCustom(customer);
		customAllotService.allot(customer,CustomerManage.NEW_CUSTOMER);
		PrintWriter out=response.getWriter();
		out.print(customer.getCusId());
	}
	@RequestMapping("/sysnMember")
	public void sysnMember() throws Exception {
	}
	
	/**
	 * 邢泽江 2016年11月16日10:49:36
	 * 
	 * 接收/拒绝 调配客户
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/receiveAllot")
	public void receiveAllot(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		try {
			String customMixAuditIds = request.getParameter("selectedIds");
			String empIds = request.getParameter("receivedPersonlist");
			String approvalState=request.getParameter("approvalState");
			//验证是否为当前登录用户所属销售
			// 获取当前登录用户
			Emp currentUser = (Emp) session.getAttribute("currentUser");
			if (null == currentUser) {
				return;
			}		
			
			String[] mixIdArray = customMixAuditIds.split(",");
			String[] empIdsArray = empIds.split(",");
			
			
			//添加销售是否在可接收客户状态？
			
			CustomMixAudit customMixAudit = new CustomMixAudit();
			String empId = "";
			
			if(approvalState.equals("3")){//3代表拒绝
				for(String mixId : mixIdArray){
					//更新申请调配表数据
					customMixAudit = customMixService.getCustomMixAuditById(mixId);
					customMixAudit.setIsEffect(approvalState);
					customMixService.updateCustomMixAudit(customMixAudit);
				}
				return;
			}
			
			for(int i = 0; i<mixIdArray.length; i++){
				
				//获取要分配的销售id
				empId = empIdsArray[i%empIdsArray.length];
				//更新申请调配表数据
				customMixAudit = customMixService.getCustomMixAuditById(mixIdArray[i]);
				customMixAudit.setApprovalerId(currentUser.getEmpno());
				customMixAudit.setToEmpId(empId);
				customMixAudit.setIsEffect(approvalState);
				customMixService.updateCustomMixAudit(customMixAudit);
				//更新客户销售关系
				empCustomRelationService.updateEmpCustomRelationByMix(empId, customMixAudit.getCusId());
				
				String[] cusid = {customMixAudit.getCusId()};
				List<Customer> customers = customerManageService.getCustomerByIdArray(cusid);
				//更新分公司，区域信息
				String deptid = customMixAudit.getToDid();
				Area area = customAllotDao.getAreaByDeptno(deptid);
				Dept dept = deptService.getDeptByDeptId(deptid);
				Customer customer = null;
				if(customers==null||area==null||dept==null){
					return;
				}else{
					customer = customers.get(0);
				}
				//打包客户信息
				packageCustomer(customer,dept,area);
				//更新客户信息
				customerManageService.updateCustomer(customer);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**邢泽江 2016年11月16日09:32:51
	 * 查询调配记录
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/findAllotRecord")
	public void findAllotRecord(PageView<CustomMixAudit> page,CustomMixAudit customMixAudit,
			HttpServletRequest request, HttpServletResponse response){
		try {
			PrintWriter pw = response.getWriter();
			//获取查询页数
			String pageStr = request.getParameter("page");
			Integer pageNow = 1;
			if(pageStr!=null&&!pageStr.equals("")){
				pageNow = Integer.parseInt(pageStr);
			}
			int pageSize = page.getPageSize();
			int startPage = pageSize*(pageNow-1);
			
			Integer rowCount = customMixService.queryMixCustomerCount(customMixAudit);
			page.setRowCount(rowCount);
			page.setPageNow(pageNow);
			page.setStartPage(startPage);
			
			PageView<CustomMixAudit> pageView = customMixService.queryMixCustomersByCondition(page,customMixAudit);
			
			String customMixListStr = mapper.writeValueAsString(pageView);
			pw.println(customMixListStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**邢泽江 
	 * 2016年11月16日09:32:40
	 * 调配接收页面
	 * @param page
	 * @param customMixAudit
	 * @param session
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/findAllotList")
	public void findAllotList(PageView<CustomMixAudit> page,CustomMixAudit customMixAudit,
			HttpSession session,HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
		
			// 获取当前登录用户
			Emp currentUser = (Emp) session.getAttribute("currentUser");
			if (null == currentUser) {
				return;
			}
			
			customMixAudit.setIsEffect("2");//获取未生效申请列表
			//获取登录用户权限下的可接收员工 可操作人员是 ：分公司经理或分公司总监
			customMixAudit.setToDid(currentUser.getId());
			
			PrintWriter pw = response.getWriter();
			//获取查询页数
			String pageStr = request.getParameter("page");
			Integer pageNow = 1;
			if(pageStr!=null&&!pageStr.equals("")){
				pageNow = Integer.parseInt(pageStr);
			}
			int pageSize = page.getPageSize();
			int startPage = pageSize*(pageNow-1);
			
			Integer rowCount = customMixService.queryMixCustomerCount(customMixAudit);
			page.setRowCount(rowCount);
			page.setPageNow(pageNow);
			page.setStartPage(startPage);
			
			PageView<CustomMixAudit> pageView = customMixService.queryMixCustomersByCondition(page,customMixAudit);
			
			String customMixListStr = mapper.writeValueAsString(pageView);
			pw.println(customMixListStr);
		
	}
	
	/**邢泽江
	 * 2016年11月16日09:33:12
	 * 处理同部门调配申请(客户所属人变更)
	 * @param page
	 * @param customMixAudit
	 * @param session
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/dealPersonChange")
	public String dealPersonChange(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws SQLException{
		
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return null;
		}			
	
		//根据参数获取客户列表
		String customerIds = request.getParameter("selectedCusId");
//		String receivedCompany = request.getParameter("receivedCompany");//直销部id+分公司id
		String receivedPerson = request.getParameter("receivedPerson");//empNo
		String mixCause = request.getParameter("mixCause");//调配理由
		
		String[] cusIdArray = customerIds.split(",");
		List<Customer> customers = customerManageService.getCustomerByIdArray(cusIdArray);
		//获取新销售信息
		Emp toEmp = empService.getEmpbyEmpno(receivedPerson);
		/*//校验是否是当前分公司所属的客户
		for(Customer c : customers){
			if(!compamyid.equals(c.getCompanyId())){
				return null;
			}
		}*/
		
		//申请调配数据插入
		CustomMixAudit customMixAudit = new CustomMixAudit();
		EmpCustomRelation empCustomRelation = new EmpCustomRelation();
		String fromEmpNo = "";
		for(Customer customer : customers){
			//下面获取客户销售关系表id , 在跨部门调配时更新客户销售关系时使用
			empCustomRelation = empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId()).get(0);
			fromEmpNo = empCustomRelation.getEmpId();
			Emp fromEmp = empService.getEmpbyEmpno(fromEmpNo);
			//修改客户销售关系
			empCustomRelationService.updateEmpCustomRelationByMix(receivedPerson, customer.getCusId());
			//初始化调配申请表数据
			customMixAudit = packageCustomMixAudit(empCustomRelation, customer,mixCause, fromEmp, toEmp, currentUser);
			//添加调配申请记录
			customMixService.addCustomMixAudit(customMixAudit);
		}
		
		return "";
	}
	
	
	/**邢泽江
	 * 2016年11月16日09:33:22
	 * 处理不同分公司调配申请
	 * @param page
	 * @param customMixAudit
	 * @param session
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/dealCompanyChange")
	public String dealCompanyChange(HttpSession session,HttpServletRequest request, HttpServletResponse response,Model model) throws SQLException{
		
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return null;
		}			
	
		//根据参数获取客户列表
		String customerIds = request.getParameter("selectedCusId");
		String receivedCompany = request.getParameter("receivedCompany");//直销部id+分公司id
//		String receivedPerson = request.getParameter("receivedPerson");//empNo
		String mixCause = request.getParameter("mixCause");//调配理由
		
		
		String[] cusIdArray = customerIds.split(",");
		List<Customer> customers = customerManageService.getCustomerByIdArray(cusIdArray);
		String[] company = receivedCompany.split(",");
		//校验是否是被分配分公司所属的客户
		for(Customer c : customers){
			if(company[0].equals(c.getCompanyId())){
				return null;
			}
		}
		
		
		//申请调配数据插入
		CustomMixAudit customMixAudit = new CustomMixAudit();
		EmpCustomRelation empCustomRelation = new EmpCustomRelation();
		String fromEmpNo = "";
		for(Customer customer : customers){
			//下面获取客户销售关系表，在跨部门调配时更新客户销售关系时使用 
			empCustomRelation = empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId()).get(0);
			fromEmpNo = empCustomRelation.getEmpId();
			Emp fromEmp = empService.getEmpbyEmpno(fromEmpNo);
			//初始化调配申请表数据
			customMixAudit = packageCustomMixAudit(empCustomRelation, customer, mixCause, fromEmp, company[1], currentUser);
			//添加调配申请记录
			customMixService.addCustomMixAudit(customMixAudit);
		}
		
		String visitSource = request.getParameter("visitSource");//调用方法页面来源
		return "redirect:/page/goCustomerQuery";
	}
	
	/**
	 * 获取客户状态变更记录
	 * @param session
	 * @param request
	 * @param response
	 * @param customer
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/getCustomerStateHistory")
	public void getCustomerStateHistory(HttpSession session,HttpServletRequest request, HttpServletResponse response, Customer customer){
		try {
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}			
		PageView<CustomStateHist> page = new PageView<CustomStateHist>();
		
		PageView<CustomStateHist> cshList = customerStateHistService.getCustomStateHistByCustomId(page,customer.getCusId());
		String customMixListStr;
		
		customMixListStr = mapper.writeValueAsString(cshList);
			
		pw.println(customMixListStr);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	}
	
	/**
	 * 邢泽江
	 * 2016年11月15日09:33:32
	 * @param emp 客户销售关系表
	 * @param mixCause 调配理由
	 * @param fromEmp 客户原销售
	 * @param toEmp 客户新分配销售
	 * @param currentUser 当前操作人
	 * @return
	 */
	private CustomMixAudit packageCustomMixAudit(EmpCustomRelation emp,Customer customer,String mixCause,Emp fromEmp,Emp toEmp,Emp currentUser){
		
		String operationContent="从"+fromEmp.getEmpno()+"  "+fromEmp.getEname()+" 调配到  "+toEmp.getEmpno()+" "+toEmp.getEname()+","+
				currentUser.getEname();
		
		CustomMixAudit customMixAudit = new CustomMixAudit();
		customMixAudit.setId(UUID.randomUUID().toString());
		customMixAudit.setEcrId(emp.getId());
		customMixAudit.setCusId(customer.getCusId());
		customMixAudit.setCname(customer.getCname());
		customMixAudit.setEmail(customer.getEmail());
		customMixAudit.setPhone(customer.getPhone());
		customMixAudit.setMixCause(mixCause);
		customMixAudit.setOperationContent(operationContent);
		customMixAudit.setFromEmpId(fromEmp.getEmpno());
		customMixAudit.setFromEmpName(fromEmp.getEname());
		customMixAudit.setToEmpId(toEmp.getEmpno());
		customMixAudit.setToEmpName(toEmp.getEname());
		customMixAudit.setApplyerId(currentUser.getEmpno());
		customMixAudit.setApprovalerId(currentUser.getEmpno());
		customMixAudit.setApprovalerId(currentUser.getEmpno());
		customMixAudit.setUpdateEname(currentUser.getEname());
		customMixAudit.setUpdateTime(DateUtil.getDefaultDate());
		customMixAudit.setIsEffect("1");//1状态即是已生效
		return customMixAudit;
	}
	
	/**
	 * 邢泽江
	 * 2016年11月14日09:33:41
	 * @param emp 客户销售关系表
	 * @param mixCause 调配理由
	 * @param fromEmp 客户原销售
	 * @param toEmp 客户新分配销售
	 * @param currentUser 当前操作人
	 * @return
	 */
	private CustomMixAudit packageCustomMixAudit(EmpCustomRelation emp,Customer customer,String mixCause,Emp fromEmp,String toEmp,Emp currentUser){
		
		String operationContent="从"+fromEmp.getEmpno()+"  "+fromEmp.getEname()+" 调配到  "+toEmp+","+
				currentUser.getEname();
		
		CustomMixAudit customMixAudit = new CustomMixAudit();
		customMixAudit.setId(UUID.randomUUID().toString());
		customMixAudit.setEcrId(emp.getId());
		customMixAudit.setCusId(customer.getCusId());
		customMixAudit.setCname(customer.getCname());
		customMixAudit.setEmail(customer.getEmail());
		customMixAudit.setPhone(customer.getPhone());
		customMixAudit.setMixCause(mixCause);
		customMixAudit.setOperationContent(operationContent);
		customMixAudit.setFromEmpId(fromEmp.getEmpno());
		customMixAudit.setFromEmpName(fromEmp.getEname());
		customMixAudit.setToEmpId("");
		customMixAudit.setToEmpName("");
		customMixAudit.setApplyerId(currentUser.getEmpno());
		customMixAudit.setApprovalerId(currentUser.getEmpno());
		customMixAudit.setUpdateEname(currentUser.getEname());
		customMixAudit.setUpdateTime(DateUtil.getDefaultDate());
		customMixAudit.setIsEffect("2");//2待接收
		customMixAudit.setToDid(toEmp);
		return customMixAudit;
	}
	
	/**
	 * 打包客户信息
	 * 2016年11月23日16:12:27
	 * @param customer
	 * @param dept
	 * @param area
	 * @return
	 */
	private Customer packageCustomer(Customer customer,Dept dept,Area area){
		customer.setRegionalId(area.getAreaID());
		customer.setAreaName(area.getName());
		customer.setCompanyId(dept.getCompanyIdStr());
		customer.setCompanyAbb(dept.getParentName());
		return customer;
	}
	
	
}
